介紹使用paramiko函式庫 進行SSH連線。
pip install paramiko
#!/usr/bin/env python
import paramiko
username = "allen"
password = "a"
hostname = "127.0.0.1"
port = 22
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username, password)
t = client.get_transport()
sftp=paramiko.SFTPClient.from_transport(t)
d = sftp.stat("/Users/allen/Dropbox/python/ssh.txt")
print (d)
client.exec_command('cd /Users/allen/Dropbox/python')
stdin, stdout, stderr = client.exec_command('ls -al')
result = stdout.readlines()
print (result)
except Exception:
print ('Exception!!')
raise